import urllib.request
import urllib.parse
import json


def create_request(page1):
    # 基础请求地址
    base_url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&'
    # 请求参数
    data = {
        'start': (page1 - 1) * 20,
        'limit': 20
    }
    # 请求 参数编码
    data = urllib.parse.urlencode(data)
    url = base_url + data
    # UA 信息
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/123.0.0.0 Safari/537.36'
    }
    # 定制请求对象
    return urllib.request.Request(url, headers=headers)


def get_content(request1):
    # 向服务器发送请求
    response = urllib.request.urlopen(request1)
    # 响应数据解码
    return response.read().decode('utf8')


def down_load(page1, content1):
    # 数据下载到本地
    fp = open('db'+str(page1)+'.json', 'w', encoding='utf-8')
    fp.write(content)


if __name__ == '__main__':
    start_page = int(input('请输入起始页:'))
    end_page = int(input('请输入结束页:'))

    for page in range(start_page, end_page+1):
        # 创建请求对象
        request = create_request(page)
        content = get_content(request)
        down_load(page, content)
        